#include "PhysicsSprite.h"

PhysicsSprite::PhysicsSprite() : m_body(NULL) {}

PhysicsSprite::~PhysicsSprite() { m_body = NULL; }

bool PhysicsSprite::initWithPhysics(const char* fileName, const CCRect& rect, b2Body *body)
{
	if (!CCSprite::initWithFile(fileName, rect)) return false;

	if (body) setPhysics(body);

	return true;
}

PhysicsSprite* PhysicsSprite::createWithPhysics(const char* fileName,  const CCRect& rect, b2Body *body)
{
	PhysicsSprite* phySp = new PhysicsSprite();

	if (phySp && phySp->initWithPhysics(fileName, rect, body)) {
		phySp->autorelease();
	} else {
		CC_SAFE_DELETE(phySp);
	}

	return phySp;
}

void PhysicsSprite::setPhysics(b2Body *body)
{
	CCAssert(body, "The param is illegal");

	body->SetUserData(this);
	m_body = body;
}

b2Body* PhysicsSprite::getPhysics() const
{
	return m_body;
}

void PhysicsSprite::updatePosition(float dt)
{
	if (!m_body) return; 

	b2Vec2 vec = m_body->GetPosition();
	this->setPosition(ccp(vec.x * PTM_RATIO, vec.y * PTM_RATIO));
	this->setRotation(-1 * CC_RADIANS_TO_DEGREES(m_body->GetAngle()));
}